import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '../views/login/login.vue')
  },
  {
    path: '/',
    component: () => import(/* webpackChunkName: "layout" */ '../views/layout/layout.vue'),
    children: [
      {
        path: '',
        name: 'home',
        component: () => import('../views/home/home.vue')
      },
      {
        path: 'articles',
        name: 'articles',
        meta: {
          title: '内容管理'
        },
        component: () => import('../views/articles/articles.vue')
      },
      {
        path: 'edit/:id',
        name: 'edit',
        meta: {
          title: '编辑文章'
        },
        component: () => import('../views/articles/edit.vue')
      },
      {
        path: 'images',
        name: 'images',
        meta: {
          title: '素材管理'
        },
        component: () => import('../views/images/images.vue')
      },
      {
        path: 'articleAdd',
        name: 'articleAdd',
        meta: {
          title: '发布文章'
        },
        component: () => import('../views/articleAdd/articleAdd.vue')
      },
      {
        path: 'comment',
        name: 'comment',
        meta: {
          title: '评论管理'
        },
        component: () => import('../views/comment/comment.vue')
      },
      {
        path: 'fans',
        name: 'fans',
        meta: {
          title: '粉丝管理'
        },
        component: () => import('../views/fans/fans.vue')
      },
      {
        path: 'settings',
        name: 'settings',
        meta: {
          title: '个人设置'
        },
        component: () => import('../views/settings/settings.vue')
      }
    ]
  },
  {
    path: '*',
    name: 'page404',
    component: () => import('../views/page404/page404.vue')
  }
]

const router = new VueRouter({
  routes
})

const pathList = ['/', '/articles', 'edit/:id', '/images', '/articleAdd', '/comment', '/fans', '/settings']
router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = 'HMPC | ' + to.meta.title
  } else {
    document.title = 'HMPC'
  }
  if (pathList.includes(to.path)) {
    if (localStorage.token) {
      next()
    } else {
      next('/login')
    }
  } else if (to.path === '/login' && localStorage.token) {
    // 如果有token不能访问登录页面
    next('/')
  } else {
    next()
  }
})

export default router
